package lego.jbv;

public class Driver extends Thread{
	private int left, right, maxSpeed;
	private double difference;
	private boolean stopNow, update;
	
	public Driver()
	{
		left = 0;
		right = 0;
		stopNow = false;
		update = false;
		maxSpeed = 100;
		difference = 0;
	}
	
	public void run()
	{
		while(!stopNow)
		{
			if(update)
			{
				update = false;
				Car.drive(left, right);
			}
			
			Thread.yield();
		}
	}
	
	public synchronized void drive(int left, int right)
	{
		if(maxSpeed < left || maxSpeed < right)
    	{
    		if(left < right)
    		{
    			difference = (double)right/(double)maxSpeed;
    		}
    		
    		else
    		{
    			difference = (double)left/(double)maxSpeed;
    		}
    		
    		left /= difference;
    		right /= difference;
    	}
		
		this.left = left;
		this.right = right;
		
		update = true;
	}

	public synchronized int getSpeed()
	{
		return (left+right)/2;
	}
	
	public synchronized void setMaxSpeed(int newMaxSpeed)
	{
		if(0 < newMaxSpeed && newMaxSpeed <= 100)
    		maxSpeed = newMaxSpeed;
    	
    	else if(100 < newMaxSpeed)
    		maxSpeed = 100;
    	
    	else
    		maxSpeed = 1;
		
		update = true;
	}
	
	public void exit()
	{
		Car.stop();
		stopNow = true;
	}
	
	
}
